<script setup lang="ts" name="UserLabelGroupForm">
import { reactive, ref } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { addUserLabelGroupApi, getUserLabelGroupDetailApi, updateUserLabelGroupApi } from '@/addon/htscrm/api'
import { t } from '@/lang'

const defaultFormData: IUserLabelGroupItem = {
    title: '',
    sort: 0
}
/** 表单实例 */
const formRef = ref<FormInstance>()
/** 表单数据 */
const formData = ref<IUserLabelGroupItem>({ ...defaultFormData })

// 表单规则
const formRules = reactive<FormRules>({
    title: [{ required: true, message: t('group.form.title.placeholder'), trigger: 'blur' }]
})

/**
   * @description 初始化
   * @param id ID
   */
function init (row?: IUserLabelGroupItem) {
    formRef.value?.resetFields()
    if (row?.id) {
        getDetail(row.id)
    } else {
        formData.value = { ...defaultFormData }
    }
}

/**
   * @description 获取详情
   * @param id ID
   */
async function getDetail (id: IUserLabelGroupItem['id']) {
    const res = await getUserLabelGroupDetailApi(id)
    formData.value = res.data
}

/**
   * @description 提交保存
   */
function submit () {
    return new Promise((resolve, reject) => {
        formRef.value?.validate(async (valid) => {
            if (valid) {
                // 表单校验
                formData.value.id
                    ? await updateUserLabelGroupApi(formData.value)
                    : await addUserLabelGroupApi(formData.value)
                ElMessage.success(t('save.success'))
                resolve(true)
            } else {
                reject(new Error(t('form.validateError')))
            }
        })
    })
}

defineExpose({
    init,
    submit
})
</script>

<template>
  <el-form class="f-form" ref="formRef" label-width="100px" :model="formData" :rules="formRules">
    <el-form-item :label="t('group.form.title')" prop="title">
      <el-input v-model="formData.title" :placeholder="t('group.form.title.placeholder')" />
    </el-form-item>
    <el-form-item :label="t('group.form.sort')" prop="sort">
      <div>
        <el-input-number v-model="formData.sort" :placeholder="t('group.form.sort.placeholder')" :min="0" :max="1000" />
        <div class="text-[#999] text-[12px]">{{ t('form.sort.tip') }}</div>
      </div>
    </el-form-item>
  </el-form>
</template>
